<?php
// Authenticates a user login.  Replies with:
// <auth>
//    <answer>true|false</answer>
//    <admin>true|false</admin>
//    PERHAPS <primaryKey>id</primaryKey> IF A STUDENT LOGS IN
// </auth>

require_once( "db.php" );
  
// Is there data coming in?
if ( isset($_POST['username'] ) ) {
 
   $username = mysql_real_escape_string( $_POST['username'] );
   $password = mysql_real_escape_string( $_POST['password'] );
   
   // First try to log the user in as an administrator.

   $query = "select id from gs_users where username='$username' and password=SHA1('$password')";
   $result = my_mysql_query( $query );
   
   if ( mysql_num_rows( $result ) > 0 ) {
      // Query returned a row.  Success!
      session_start();
      $_SESSION['adminLoggedIn'] = 'true';
      echo "<auth><answer>true</answer><admin>true</admin></auth>";
      return;
   }
   
   // Okay, so that didn't work.  Try to log the user in as a student.
   // Username should be the last four digits of their SID.
   // Password should be their birthday (YYMMDD).
   
   $query = "select id from gs_students where sid='$username' and birthday='$password'";
   $result = my_mysql_query( $query );
   $row = mysql_fetch_object($result);
   
   if ( mysql_num_rows( $result ) > 0 ) {
      // Query returned a row.  Success!
      session_start();
      $_SESSION['studentLoggedIn'] = 'true';
      $_SESSION['studentId'] = $row->id;
      echo "<auth><answer>true</answer><admin>false</admin><primaryKey>$row->id</primaryKey></auth>";
      return;
   }
   
}

// If we get here, login failed.
echo "<auth><answer>false</answer><admin>false</admin></auth>";

?>